# 购物车
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse


def add(request, pid):
    """ 添加 """
    # 从session中获取所有的菜品，再根据拿到的菜品id号获取要放入购物车的菜品
    product = request.session['product_list'][pid]
    product['num'] = 1  # 初始化当前菜品的购买量

    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cart_list', {})
    # 判断购物车中是否有存在的菜品信息
    if pid in cart_list:
        # 存在就加
        cart_list[pid]['num'] += product['num']
    else:
        # 没有就放入
        cart_list[pid] = product

    # 将cart_list放入购物车
    request.session['cart_list'] = cart_list
    print(cart_list)

    return redirect(reverse('web_index'))


def delete(request, pid):
    """ 删除 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cart_list', {})
    del cart_list[pid]

    # 删除后再再放回session中
    request.session['cart_list'] = cart_list
    return redirect(reverse('web_index'))


def clear(request):
    """ 清空 """
    request.session['cart_list'] = {}
    return redirect(reverse('web_index'))


def change(request):
    """ 更改 """
    # 尝试从session中获取名字为cart_list的购物车信息，没有返回{}
    cart_list = request.session.get('cart_list', {})
    # 获取要更改的菜品id
    pid = request.GET.get('pid', 0)
    m = int(request.GET.get('num', 1))  # 更改的数量
    if m < 1:
        m = 1

    # 修改数量
    cart_list[pid]['num'] = m
    # 更改后再再放回session中
    request.session['cart_list'] = cart_list

    return redirect(reverse('web_index'))
